package org.linlinjava.litemall.admin.service;

import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.domain.LitemallOrderGoods;
import org.linlinjava.litemall.db.domain.LitemallSpell;
import org.linlinjava.litemall.db.domain.UserVo;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.LitemallSpellService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.util.BalanceConstant;
import org.linlinjava.litemall.db.util.OrderSpellConstant;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.util.SpellConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminSpellService {
    @Autowired
    private LitemallSpellService spellService;
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;

    public void fail(Integer spellId) {
        Boolean isCreator = true;
        LitemallSpell creator;
        LitemallSpell spell = spellService.findById(spellId);
        if (!spell.getSpellId().equals(0)) { // 非创建者
            creator = spellService.findById(spell.getSpellId());
            isCreator = false;
        } else {
            creator = spell;
        }
        if (creator.getStatus().equals(SpellConstant.STATUS_SUCCESS)) { //拼单已成功
            if (isCreator) { // 创建者退款
//                throw new RuntimeException("拼单已成功，不允许退款");
                spellService.fail(creator);
                BigDecimal amount = userService.addBalance(creator.getCreatorUserId(), creator.getReducePrice().negate(), BalanceConstant.SPELL);
                if (amount == null) {
                    throw new RuntimeException("该用户余额不足，无法完成退款");
                }
            } else { // 参与者退款
                spellService.fail(creator);
                // 收回创建者的奖励
//                userService.addBalance(creator.getCreatorUserId(), creator.getReducePrice().negate(), BalanceConstant.SPELL);
            }
        } else if (creator.getStatus().equals(SpellConstant.STATUS_FAIL)) {//拼单已失败
            // 不管
        } else { //拼单正在进行中
            spellService.fail(creator);
        }
    }

    public Object detail(Integer id) {
        LitemallSpell spell = spellService.findById(id);
        if (spell == null) {
            return ResponseUtil.fail();
        }
        LitemallOrder order = orderService.findById(spell.getOrderId());
        return ResponseUtil.ok(info(order, spell));
    }

    /**
     * 拼单具体详情
     */
    public Map<String, Object> info(LitemallOrder order, LitemallSpell spell) {
        Map<String, Object> orderVo = new HashMap<String, Object>();
        orderVo.put("id", order.getId());
        orderVo.put("orderSn", order.getOrderSn());
        orderVo.put("goodsPrice", order.getGoodsPrice());
        orderVo.put("freightPrice", order.getFreightPrice());
        orderVo.put("actualPrice", order.getActualPrice());
        LitemallOrderGoods orderGoods = orderGoodsService.queryOneGoodsByOid(order.getId());
        Map<String, Object> result = new HashMap<>();
        result.put("orderInfo", orderVo);
        result.put("orderGoods", orderGoods);
        UserVo creator = userService.findUserVoById(spell.getCreatorUserId());
        List<UserVo> joiners = new ArrayList<>();
        joiners.add(creator);
        if (spell.getSpellId() == 0) { // 本身是发起者
            LitemallSpell spellJoiner = spellService.queryJoinRecord(spell.getId());
            if (spellJoiner != null) {
                UserVo joiner = userService.findUserVoById(spellJoiner.getUserId());
                joiners.add(joiner);
            }
        } else { // 本身是一个参与者
            UserVo joiner = userService.findUserVoById(spell.getUserId());
            joiners.add(joiner);
        }
        result.put("creator", creator);
        result.put("joiners", joiners);
        result.put("spell", spell);
        LocalDateTime addTime = spell.getAddTime();
        LocalDateTime nowTime = LocalDateTime.now();
        long pastTime = Duration.between(addTime, nowTime).toMillis();
        Integer allTime = SystemConfig.getSpellUnpaid() * 60 * 1000;
        result.put("leftTime", (allTime - pastTime) / 1000);
        return result;
    }
}
